import '@ant-design/compatible/assets/index.css';
import { Modal, Button, Table, Radio, Input, message } from 'antd';
import React, { useState, useEffect } from 'react';
import { useRequest } from '@umijs/hooks';
import styles from './style.less'
import { fileDownload } from '@/utils/downExcel';
import { awaitScrapArticlesPageList, scrapProductsUnderScrapList } from '../service'

const ExtendScrapDateTable = props => {
  const { extendScrapDateVisible, scrapNum, onCancel, onSubmit: handleConfirmScrap } = props;

  // 单选值
  const [scrapOperation, handleScrapOperation] = useState({})
  // 表格多选选项
  const [selectedRowKeys, handleSelectedRowKeys] = useState([])
  // 表格状态
  const [scrapStatus, handleScrapStatus] = useState({ prolongs: {}, recycles: [], scraps: [] })
  // 导出国际按钮loading
  const [outLoading, handleOutLoading] = useState(false)
  // 导出国内按钮loading
  const [inLoading, handleInLoading] = useState(false)
  // 延长时间
  const [prolongValue, handleProlongValue] = useState({})


  // 操作单选
  const plainOptions = [
    {
      label: '报废',
      value: '0'
    },
    {
      label: '回收',
      value: '1'
    },
    {
      label: '延长',
      value: '2'
    }
  ];

  // 获取待报废物品分页接口
  const { data: awaitScrapArticlesPageListD = { data: [] }, run: awaitScrapArticlesPageListR } = useRequest(params => awaitScrapArticlesPageList(params), {
    manual: true
  })
  // 导出报表接口
  const { run: scrapProductsUnderScrapListR } = useRequest(params => scrapProductsUnderScrapList(params), {
    manual: true,
    onSuccess: data => {
      handleOutLoading(false)
      handleInLoading(false)
      fileDownload(
        data,
        '报废物品信息数据.xlsx'
      );
    },
  });

  // 多选
  const rowSelection = {
    selectedRowKeys,
    onChange: (selectedRowKeys) => {
      handleSelectedRowKeys(selectedRowKeys)
    }
  };

  // 过滤遗失物品类别
  const fitlerLostCategory = (v) => {
    if (v === 1) {
      return '食品、药品、保健品、香烟、酒水等入口物品，生活日用品、服装鞋帽、工艺品（含字画）、书籍等无价值物品'
    } else if (v === 2) {
      return '鲜活、易腐物品'
    } else if (v === 3) {
      return '军用品、历史文物、珍贵图书类'
    } else if (v === 4) {
      return '珠宝玉石、证件、银行卡等物品'
    } else if (v === 5) {
      return '现金、有价票据、贵金属'
    } else if (v === 6) {
      return '电子类、虫草类物品'
    } else if (v === 7) {
      return '违禁物品'
    } else if (v === 8) {
      return '贵重物品'
    }
  }

  // 改变待报废物品状态
  const changeStatus = (e, lostNumber) => {
    handleScrapOperation({ ...scrapOperation, [lostNumber]: e.target.value })
    if (e.target.value === '0') {
      let recyclesArr = scrapStatus.recycles
      let prolongsObj = scrapStatus.prolongs
      if (recyclesArr.indexOf(lostNumber) !== -1) {
        recyclesArr.splice(recyclesArr.indexOf(lostNumber), 1)
      }
      if (prolongsObj[lostNumber]) {
        delete prolongsObj[lostNumber]
      }
      handleScrapStatus({ prolongs: prolongsObj, recycles: recyclesArr, scraps: [...scrapStatus.scraps, lostNumber] })
    } else if (e.target.value === '1') {
      let scrapsArr = scrapStatus.scraps
      let prolongsObj = scrapStatus.prolongs
      if (scrapsArr.indexOf(lostNumber) !== -1) {
        scrapsArr.splice(scrapsArr.indexOf(lostNumber), 1)
      }
      if (prolongsObj[lostNumber]) {
        delete prolongsObj[lostNumber]
      }
      handleScrapStatus({ prolongs: prolongsObj, scraps: scrapsArr, recycles: [...scrapStatus.recycles, lostNumber] })
    } else if (e.target.value === '2') {
      let recyclesArr = scrapStatus.recycles
      let scrapsArr = scrapStatus.scraps
      if (recyclesArr.indexOf(lostNumber) !== -1) {
        recyclesArr.splice(recyclesArr.indexOf(lostNumber), 1)
      }
      if (scrapsArr.indexOf(lostNumber) !== -1) {
        scrapsArr.splice(scrapsArr.indexOf(lostNumber), 1)
      }
      handleScrapStatus({ scraps: scrapsArr, recycles: recyclesArr, prolongs: { ...scrapStatus.prolongs, [lostNumber]: 1 } })
    }
  }

  // 改变延长时间
  const changeInput = (e, lostNumber) => {
    if (e.target.value > 365) {
      handleProlongValue({ ...prolongValue, [lostNumber]: 365 })
      handleScrapStatus({ ...scrapStatus, prolongs: { ...scrapStatus.prolongs, [lostNumber]: 365 } })
    } else if (e.target.value < 1) {
      handleProlongValue({ ...prolongValue, [lostNumber]: 1 })
      handleScrapStatus({ ...scrapStatus, prolongs: { ...scrapStatus.prolongs, [lostNumber]: 1 } })
    } else {
      handleProlongValue({ ...prolongValue, [lostNumber]: e.target.value })
      handleScrapStatus({ ...scrapStatus, prolongs: { ...scrapStatus.prolongs, [lostNumber]: e.target.value } })
    }
  }

  // 导出
  const exportCharts = (val) => {
    if (awaitScrapArticlesPageListD.data.length === 0) {
      message.warning('表格数据为空');
    } else {
      if (val === 2) {
        handleOutLoading(true)
      } else {
        handleInLoading(true)
      }
      scrapProductsUnderScrapListR({ scrapNumber: scrapNum, type: val });
    }
  };

  // 确认
  const okHandle = () => {
    handleConfirmScrap({ ...scrapStatus, scrapNumber: scrapNum })
  };

  // 改变页码
  const pageChange = (page, pageSize) => {
    awaitScrapArticlesPageListR({ scrapNumber: scrapNum, current: page, pageSize: pageSize })
  }

  useEffect(() => {
    awaitScrapArticlesPageListR({ scrapNumber: scrapNum, current: 1, pageSize: 20 })
  }, [])

  const columns = [
    {
      title: '遗失物品编号',
      width: 140,
      dataIndex: 'lostNumber',
      render: (text, _) => (<a>{text}</a>),
    },
    {
      title: '遗失物品类型',
      dataIndex: 'lostCategory',
      width: 150,
      render: (text, record) => (
        <div className={styles.lostItemType} title={fitlerLostCategory(text)}>{fitlerLostCategory(text)}</div>
      )
    },
    {
      title: '遗失物品名称',
      dataIndex: 'lostArticlesName',
      width: 150,
      render: (text, _) => (<span>{text}</span>),
      ellipsis: true
    },
    {
      title: '报废日期',
      width: 120,
      dataIndex: 'scrapTime',
      ellipsis: true
    },
    {
      title: '操作',
      key: 'option',
      dataIndex: 'option',
      valueType: 'option',
      width: 350,
      render: (_, record) => (
        <div className={styles.option}>
          <Radio.Group options={plainOptions} onChange={(e) => changeStatus(e, record.lostNumber)} defaultValue='0' />
          <Input addonAfter="天" placeholder='请输入' value={prolongValue !== {} ? prolongValue[record.lostNumber] : ''} disabled={scrapOperation[record.lostNumber] !== '2' ? true : false} onChange={(e) => changeInput(e, record.lostNumber)} />
        </div>
      )
    },
  ];

  return (
    <>
      <Modal
        className={styles.extendScrapDateTable}
        title={[
          <div key="title">延长报废日期</div>
        ]}
        width='1020px'
        visible={extendScrapDateVisible}
        onOk={okHandle}
        onCancel={() => onCancel()}
      >
        <p>
          <Button type="primary" className={styles.exportBtn} onClick={() => exportCharts(2)} loading={outLoading}>
            导出国际
          </Button>
          <Button type="primary" onClick={() => exportCharts(1)} loading={inLoading}>
            导出国内
          </Button>
        </p>
        <Table
          rowKey='lostNumber'
          rowSelection={rowSelection}
          columns={columns}
          dataSource={awaitScrapArticlesPageListD.data}
          pagination={{
            showSizeChanger: true,
            showQuickJumper: true,
            total: awaitScrapArticlesPageListD.total,
            showTotal: (total, range) => `第${range[0]}-${range[1]}条 共 ${total} 项`,
            defaultPageSize: 20,
            pageSizeOptions: ['20', '30', '40'],
            onChange: pageChange,
            onShowSizeChange: pageChange
          }}
        />
      </Modal>
    </>
  );
};

export default ExtendScrapDateTable;
